package com.southwind.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.southwind.entity.User;
import com.southwind.exception.ShopException;
import com.southwind.form.UserForm;
import com.southwind.form.UserLoginForm;
import com.southwind.result.ResponseEnum;
import com.southwind.service.UserService;
import com.southwind.util.JwtUtil;
import com.southwind.util.MD5Util;
import com.southwind.util.ResultVOUtil;
import com.southwind.vo.ResultVO;
import com.southwind.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author southwind
 * @since 2023-12-31
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResultVO register(@RequestBody UserForm userForm){
        User user = new User();
        user.setPassword(MD5Util.getSaltMD5(userForm.getPassword()));
        user.setMobile(userForm.getMobile());
        this.userService.save(user);
        return ResultVOUtil.success(null);
    }

    @GetMapping("/login")
    public ResultVO login(UserLoginForm userLoginForm){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", userLoginForm.getMobile());
        User one = this.userService.getOne(queryWrapper);
        if(one == null) throw new ShopException(ResponseEnum.MOBILE_ERROR.getMsg());
        boolean saltverifyMD5 = MD5Util.getSaltverifyMD5(userLoginForm.getPassword(), one.getPassword());
        if(!saltverifyMD5) throw new ShopException(ResponseEnum.PASSWORD_ERROR.getMsg());
        UserVO userVO = new UserVO();
        userVO.setMobile(userLoginForm.getMobile());
        userVO.setPassword(one.getPassword());
        userVO.setUserId(one.getUserId());
        userVO.setToken(JwtUtil.createToken(one.getUserId(), one.getMobile()));
        return ResultVOUtil.success(userVO);
    }

    @GetMapping("/checkToken")
    public ResultVO checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        boolean result = JwtUtil.checkToken(token);
        if(result) return ResultVOUtil.success(null);
        return ResultVOUtil.fail(ResponseEnum.LOGIN_ERROR.getMsg());
    }


}

